package com.device.common.util;

import java.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lgb
 * @date 2020年6月8日 下午8:17:22
 * Copyright (C) 深圳工勘科技
 * @说明: Threads
 **/
@Slf4j
public class Threads {
	
    /**
     *  @return sleep等待,单位为毫秒
     **/
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            return;
        }
    }

    /**
     * @return 停止线程池
     * @return 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * @return 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * @return 如果仍人超時，則強制退出.
     * @return 另对在shutdown时线程本身被调用中断做了处理.
     **/
    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        log.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * @return 打印线程异常信息
     **/
    public static void printException(Runnable r,Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            log.error(t.getMessage(), t);
        }
    }
    
}